package com.pb.interceptor;

import com.pb.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //1、获取请求路径
//        String path = request.getRequestURI();///login
//        //2、判断是否是登录请求，如果是登录请求，放行
//        if(path.contains("/login")){
//            log.info("登录请求，放行：{}",path);
//            return true;
//        }
        //3、获取请求头中的token
        String token = request.getHeader("token");
        //4、判断token是否为空，如果为空，返回401
        if(token == null|| token.isEmpty()){
            log.info("请求头token为空，返回401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //5、如果token不为空，解析token，如果解析失败，返回401
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.info("解析令牌失败，返回401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //6、校验通过，放行
        log.info("令牌校验通过，放行");
        return true;
    }
}
